<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索区域 -->
          <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select" clearable
            @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column type="index" label="序号" />
        <!-- <el-table-column prop="id" label="用户ID" width="180" /> -->
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="mobile" label="联系方式" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row.mg_state}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="账号创建时间" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="showupdateDilog(scope.row.id)" />
            <el-button icon="el-icon-delete" type="danger" size="mini" @click="removeUserById(scope.row.id)" />
            <el-tooltip content="分配角色" placement="top" effect="light" :enterable="false">
              <el-button icon="el-icon-setting" type="warning" size="mini" @click="setRoleDialogVisible(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
        <!-- 内容主题 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" id="name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" id="pwd"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" id="email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile" id="phone"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改信息对话框 -->
      <el-dialog title="修改用户" :visible.sync="updateDialogVisible" width="50%" @close="updateDialogClose">
        <!-- 内容主题 -->
        <el-form :model="updateForm" :rules="updateFormRules" ref="updateFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="updateForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="updateForm.email" id="email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="updateForm.mobile" id="phone"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 弹出消息框 -->
    <el-dialog title="角色分配" :visible.sync="RoleDialogVisible" width="30%">
      <p>用户名：{{userInfo.username}}</p>
      <p>当前角色：{{userInfo.role_name}}</p>
      <el-select v-model="selectedroleId" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created () {
    this.getUserList()
    this.getRoleList()
  },
  data () {
    var checkEmail = (rules, value, callback) => {
      const reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rules, value, callback) => {
      const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入11位的手机号'))
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      //对话框隐藏
      addDialogVisible: false,
      updateDialogVisible: false,
      //添加表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      RoleDialogVisible: false,
      //修改updateForm

      updateForm: {},
      userInfo: {},
      roleList: [],
      //已选择的角色
      selectedroleId: '',

      //表单规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名字符在3到10之间', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码字符在6到15之间', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      //修改表单验证规则
      updateFormRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码字符在6到15之间', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      }
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听显示数据条数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件(翻页)
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()

    },
    //获取分配角色
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('角色数据获取失败')
      }
      this.$message.success('角色数据获取成功')
      this.roleList = res.data
    },
    //回调状态信息
    async userStateChanged (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error("状态修改失败，请检查网络")
      }
      this.$message.success("更新状态成功")
    },
    //添加预验证
    addUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        //发起请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    //修改信息退出重置
    updateDialogClose () {
      this.$refs.updateFormRef.resetFields()
    },
    //根据id查询用户信息
    async showupdateDilog (id) {
      this.updateDialogVisible = true
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.updateForm = res.data
    },
    //用户信息提交
    updateInfo () {
      this.$refs.updateFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改请求
        const { data: res } = await this.$http.put('users/' + this.updateForm.id, {
          email: this.updateForm.email,
          mobile: this.updateForm.mobile,
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新数据失败')
        }
        //关闭对话框
        this.updateDialogVisible = false
        this.getUserList()
        this.$message.success('更新数据成功')
      })
    },
    //按id删除用户信息
    async removeUserById (id) {
      const result = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('请检查网络')
      this.$message.success("删除用户成功")
      this.getUserList()
    },
    //分配角色
    async setRoleDialogVisible (userInfo) {
      this.userInfo = userInfo
      this.RoleDialogVisible = true
      const { data: res } = await this.$http.get('roles/')
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.RoleForm = res.data
    },
    //提交角色分配
    //分配后端有问题，400
    async saveRoleInfo (userInfo) {
      if (!this.selectedroleId) {
        return this.$message.error('请选择角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedroleId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败，请检查网络')
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false

    }
  }
}
</script>
<style scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>